package top.zhaoyuliu.logbook.server.connect.server;

import org.tio.client.intf.ClientAioHandler;
import org.tio.core.ChannelContext;
import org.tio.core.intf.Packet;
import org.tio.server.intf.ServerAioHandler;

import lombok.extern.slf4j.Slf4j;
import top.zhaoyuliu.logbook.client.connect.base.AbstractAioHandler;
import top.zhaoyuliu.logbook.client.connect.packet.LbPacket;
import top.zhaoyuliu.logbook.client.connect.packet.PacketBuilder;
import top.zhaoyuliu.logbook.client.connect.packet.PacketType;
import top.zhaoyuliu.logbook.client.thread.ThreadPool;
import top.zhaoyuliu.logbook.client.utils.ApplicationContextProvider;
import top.zhaoyuliu.logbook.server.connect.factory.HandlerFactory;

/**
 * 
 * Copyright © 2021 Arain. All rights reserved.
 *
 * @Title: BlockServerAioHandler.java
 * @Prject: logbook-server
 * @Package: top.zhaoyuliu.logbook.server.connect.server
 * @Description: <功能详细描述>
 * @author: Arain
 * @date: 2021年1月22日 下午4:52:58
 * @version: V1.0
 */
@Slf4j
public class LbServerAioHandler extends AbstractAioHandler implements ServerAioHandler,ClientAioHandler {

	/**
	 * 自己是server，此处接收到客户端来的消息。这里是入口
	 */
	@Override
	public void handler(Packet packet, ChannelContext channelContext) {
		ThreadPool.INSTANCE.executor().execute(new Runnable() {
			@Override
			public void run() {
				LbPacket blockPacket = (LbPacket) packet;
				byte type = blockPacket.getType();
				byte[] body = blockPacket.getBody();
				String data = new String(body);
				log.info("type -> {} ,msg -> {}", type, data);
				ApplicationContextProvider.getBean(HandlerFactory.class).exec(type).handler(data,channelContext);
			}
		});

	}

	@Override
	public Packet heartbeatPacket(ChannelContext channelContext) {
		LbPacket packet = new PacketBuilder().setType(PacketType.HEART_BEAT).build();
		return packet;
	}
}
